package pers.vic.system.system.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vic.base.attachment.service.AttachmentService;
import pers.vic.base.bo.system.SysMenu;
import pers.vic.base.pager.Lookup;
import pers.vic.base.pager.PageInfo;
import pers.vic.base.service.BaseService;
import pers.vic.system.system.mapper.SysMenuMapper;

/**
 * 菜单表
 *
 */
@Service
public class SysMenuService extends BaseService {

	@Resource
	private SysMenuMapper sysMenuMapper;
	
	@Resource
	private AttachmentService attachmentService;

	/**
	 * 查询列表
	 */
	public PageInfo<SysMenu> list(Lookup lookup) {
		startPage(lookup);
		List<SysMenu> datas = sysMenuMapper.list(lookup);
		return PageInfo.instance(datas, lookup);
	}
	/**
	 * 全部菜单
	 * @return
	 */
	public List<SysMenu> all() {
		return sysMenuMapper.list(new Lookup());
	}
	

	/**
	 * 根据主键查询
	 */
	public SysMenu findById(int id) {
		return sysMenuMapper.findById(id);
	}
	
	/**
	 * 根据主键数组查询
	 */
	public List<SysMenu> findByIds(int... ids) {
		return sysMenuMapper.findByIds(ids);
	}

	/**
	 * 新增
	 */
	@Transactional
	public int insert(SysMenu entity) {
		attachmentService.addAttachmengFromObj(entity);
		return sysMenuMapper.insert(entity);
	}

	/**
	 * 修改
	 */
	@Transactional
	public int update(SysMenu entity) {
		SysMenu old = findById(entity.getId());
		attachmentService.handleOldAndNowAttachment(old, entity);
		return sysMenuMapper.update(entity);
	}

	/***
	 * 删除
	 */
	@Transactional
	public int delete(int... ids) {
		List<SysMenu> olds = findByIds(ids);
		attachmentService.deleteAttachmengFromObj(olds);
		return sysMenuMapper.delete(ids);
	}
	/**
	 * 构建树形结构的菜单树
	 */
	public List<SysMenu> getAuthorityMenu(int userId){
		List<SysMenu> list = getUserMenus(userId);
		return  buildMenuTree(list);
	}
	
	/**
	 * 获得用户菜单树列表
	 * @return
	 */
	public List<SysMenu> getUserMenus(int userId){
		return sysMenuMapper.getUserMenus(userId);
	}
	/**
	 * 构建菜单树方法
	 * @param list
	 * @return
	 */
	private List<SysMenu> buildMenuTree(List<SysMenu> list){
		Map<Integer, SysMenu> menuMap = new LinkedHashMap <Integer, SysMenu>();
		List<SysMenu> menuTree = new ArrayList<SysMenu>(); 
		for(SysMenu m : list) {
			menuMap.put(m.getId(), m);
		}
		for(Map.Entry<Integer, SysMenu> entry : menuMap.entrySet()) {
			SysMenu menu = entry.getValue();
			if(menu.isRoot()) {//根节点
				menuTree.add(menu);
			}else {//子节点
				SysMenu parent = menuMap.get(menu.getPid());
				if(parent != null) {
					parent.addChildren(menu);
				}
			}
		}
		return  menuTree;
		
	}

}
